package club.janna.jrpc.rpc.protocol.jrpc;

import club.janna.jrpc.remoting.Channel;
import club.janna.jrpc.remoting.ServerHandler;
import club.janna.jrpc.rpc.Invoker;
import club.janna.jrpc.rpc.RPCInvocation;
import club.janna.jrpc.rpc.RPCResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JRPCServerHandler implements ServerHandler {

    /**
     * invoker映射
     */
    private Map<Class<?>, Invoker> invokerMap = new HashMap<>();

    @Override
    public void handleReceive(Channel channel, Object obj) {
        RPCInvocation invocation = (RPCInvocation) obj;
        log.info("处理方法的调用 -> {}", invocation);
        if(!invokerMap.containsKey(invocation.getTarget())) {
            throw new RuntimeException("没有找到对应的服务, " + invocation.getTarget().getName());
        }
        // 获取对应服务的invoker，调用方法
        RPCResponse<?> rpcResponse = invokerMap.get(invocation.getTarget()).invoker(invocation);
        channel.send(rpcResponse);
    }

    @Override
    public void register(Class<?> iClass, Invoker invoker) {
        invokerMap.put(iClass, invoker);
    }
}
